package eva.savant.core.printer;

import javax.print.*;
import javax.swing.JOptionPane;

public class Printer extends Thread {

    String printFile[];

    PrinterApplet printerApplet;
    
    public Printer(PrinterApplet printerapplet, String txt) {

        printerApplet = printerapplet;

        printFile = txt.split("\n");
    }
    
    private byte[] getBytesTextPOS(String txt) {

        char chars[] = txt.toCharArray();

        byte array[] = new byte[chars.length];

        for(int i= 0; i < chars.length; i++) {

             if(chars[i] ==    '$') array[i] = (byte)27;

        else if(chars[i] ==    '*') array[i] = (byte)29;

        else if(chars[i] ==    'ñ') array[i] = (byte)164;

        else if(chars[i] ==    'Ñ') array[i] = (byte)165; //165 ascii del caracter Ñ

        else if(chars[i] ==    '?') array[i] = (byte) 1; // ignora caracter imprimir

        else if(chars[i] == '\277') array[i] = (byte) 1; // ignora caracter imprimir

        else array[i] = (byte)chars[i];

        }

        return array;
    }

    private void printText(String txt) {

        byte array[] = getBytesTextPOS(txt);

        try {

            PrintService printservice = PrintServiceLookup.lookupDefaultPrintService();

            DocPrintJob docprintjob = printservice.createPrintJob();

            SimpleDoc simpledoc = new SimpleDoc(array, javax.print.DocFlavor.BYTE_ARRAY.AUTOSENSE, null);

            try { docprintjob.print(simpledoc, null); }

            catch(PrintException printexception) { JOptionPane.showMessageDialog(printerApplet, printexception); }

        } catch(Exception exception) {

            JOptionPane.showMessageDialog(printerApplet, exception);
        }
    }

    public void run() {

        String txt = "$@";


        for (String txtFile : printFile) txt = txt + "\r" + txtFile;


        txt = txt + "\n\n\n\n\n\n\n\r*V1"; //cortar papel


        printText(txt);
    }
    
}
